package com.ficus.road.maintain.core.model;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ficus.road.maintain.core.model.smartnew.SmartDecisionExcel;
import com.ficus.road.maintain.core.model.smartnew.annotation.Excel;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @className: HitExcelVO
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2025/1/16
 **/
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
public class HitExcelVO extends SmartDecisionExcel {

    @Excel("病害ID")
    private String hitId;
    @Excel(value = "发现时间", type = CellType.FORMULA)
    private Long hitTime;

    @Excel("病害名称")
    private String hitName;

    @Excel("病害详情（起点桩号，终点桩号，病害坐标等）")
    private String detail;


    public HitExcelVO(HitExcelVO vo) {
        this.hitId = vo.getHitId();
        this.hitTime = vo.getHitTime();
        this.hitName = vo.getHitName();
        this.detail = vo.getDetail();
    }

    public HitExcelVO() {
    }

    public Hit convertHit(){
        Hit hit = new Hit();
//        hit.setId(this.getHitId());
//        hit.setCreationTime(this.getHitTime());
//        hit.setHitTime(this.getHitTime());
//        hit.setType(this.getHitName());
        try{
        String detail =this.getDetail();
        detail=detail.replaceAll("'","\"").replaceAll("True","true").replaceAll("False","false");

            JSONArray jsonArray = JSONArray.parseArray(detail);
            if(jsonArray.size()>0)
            {
                JSONObject jsonHit = jsonArray.getJSONObject(0);
                JSONObject jsonAttrs=jsonHit.getJSONObject("attrs");
                JSONArray jsonSubjects=jsonHit.getJSONArray("subjects");


                //初始化attrs
                HitAttrs attrs = new HitAttrs();
                attrs.setConfirmation(Confirmation.builder().status(Confirmation.ConfirmationStatus.CORRECT).build());
//                attrs.setSectionCode(request.getSectionCode());
             //   attrs.setLocation(Lists.newArrayList(request.getLgt(),request.getLat()));
                attrs.setGpsLocation(GpsLocation.builder().latitude(jsonAttrs.getJSONObject("gps_location").getDouble("latitude")).longitude(jsonAttrs.getJSONObject("gps_location").getDouble("longitude")).build());
                //attrs.setDescriptionThird(request.getDescription());
                attrs.setDiseaseUid(jsonAttrs.getString("disease_uid"));
                //attrs.setTraCongestionIndex(request.getTraCongestionIndex());

                if (!org.springframework.util.StringUtils.isEmpty(jsonAttrs.getString("scene_image"))) {
                    String url=jsonAttrs.getString("scene_image");
                    attrs.setSceneImage(url);
                    attrs.setSceneImageName(url.substring(url.indexOf("com") + 4));
                }
                attrs.setStatus(HitStatusEnum.fromValue(jsonAttrs.getString("status")));
                attrs.setCarId(jsonAttrs.getString("card_id"));
                hit.setAttrs(attrs);


                //初始化subjects
                if (CollectionUtils.isEmpty(jsonSubjects)) {
                    hit.setSubjects(Lists.newArrayList());
                } else {
                    List<HitSubject> subjects = new ArrayList<>();
                    for (int i = 0; i <jsonSubjects.size() ; i++) {
                        JSONObject jsonSub = jsonSubjects.getJSONObject(i);
                        HitSubject hitSubject = new HitSubject();
                        hitSubject.setArea(jsonSub.getFloat("area"));
                        hitSubject.setRelBbox(RelBbox.builder()
                                .h(jsonSub.getJSONObject("rel_bbox").getDouble("h"))
                                .w(jsonSub.getJSONObject("rel_bbox").getDouble("w"))
                                .y(jsonSub.getJSONObject("rel_bbox").getDouble("y"))
                                .x(jsonSub.getJSONObject("rel_bbox").getDouble("x"))
                                .build());
                        hitSubject.setNeedPushOut(jsonSub.getBoolean("need_push_out"));
                        if(jsonSub.getJSONObject("bbox")!=null) {
                            hitSubject.setBbox(Bbox.builder()
                                    .h(jsonSub.getJSONObject("bbox").getInteger("h"))
                                    .w(jsonSub.getJSONObject("bbox").getInteger("w"))
                                    .y(jsonSub.getJSONObject("bbox").getInteger("y"))
                                    .x(jsonSub.getJSONObject("bbox").getInteger("x"))
                                    .build());
                        }
                        hitSubject.setLength(jsonSub.getFloat("length"));
                        hitSubject.setType(jsonSub.getString("type"));
                        hitSubject.setHeightDiff(jsonSub.getInteger("height_diff"));
                        hitSubject.setFallDownNumber(jsonSub.getInteger("fall_down_number"));
                        hitSubject.setDiseaseUid(jsonSub.getString("disease_uid"));
                        if(jsonSub.getString("severity_type")!=null)
                        {
                            hitSubject.setSeverityType(SeverityType.fromValue(jsonSub.getString("severity_type")));
                        }
                        hitSubject.setRoadType(jsonSub.getString("road_type"));
                        hitSubject.setWidth(jsonSub.getInteger("width"));
                        hitSubject.setAngle(jsonSub.getFloat("angle"));
                        if(jsonSub.getString("status")!=null) {
                            hitSubject.setStatus(HitStatusEnum.fromValue(jsonSub.getString("status")));
                        }

                        hit.setNeedPushOut(jsonSub.getBoolean("need_push_out"));
                        if(jsonSub.getString("severity_type")!=null) {
                            hit.setSeverityType(SeverityType.fromValue(jsonSub.getString("severity_type")));
                        }

                        subjects.add(hitSubject);
                    }
                    hit.setSubjects(subjects);
                }


                hit.setLength(jsonHit.getFloat("length"));
                hit.setArea(jsonHit.getFloat("area"));
                hit.setAngle(jsonHit.getFloat("angle"));
                hit.setHeightDiff(jsonHit.getInteger("height_diff"));
                hit.setFallDownNumber(jsonHit.getInteger("fall_down_number"));
                hit.setRoadType(jsonHit.getString("road_type"));
                hit.setScene("CITY");
                hit.setClassification("SECURITY");
                hit.setType(jsonHit.getString("type"));
                hit.setHitTime(jsonHit.getLong("hit_time"));
                hit.setFirstHitTime(jsonHit.getLong("first_hit_time")==null?jsonHit.getLong("hit_time"):jsonHit.getLong("first_hit_time"));
                if(this.hitName!=null)
                {
                    hit.setType(this.getHitName());
                }
                hit.setCreationTime(jsonHit.getLong("hit_time"));
                hit.setWidth(jsonHit.getInteger("width"));
                hit.setId(this.getHitId());
                hit.setList(Lists.newArrayList(HistoryHit.fromHit(hit)));
                hit.setLastModificationTime(System.currentTimeMillis() / 1000);
                return hit;
            }
            else
            {
                return null;
            }
        }catch (Exception e)
        {
            log.info("转换错误:"+this.getHitId());
            return null;
        }
    }

    public static void main(String[] args) {
        HitExcelVO hitExcelVO = new HitExcelVO();
        hitExcelVO.setDetail("[{'road_type': 'ROAD_TYPE_UNKNOWN', 'length': 0.0, 'attrs': {'car_id': 'YTKJ20210056', 'status': 'NEW', 'scene_image': 'http://yitu-aicar.oss-cn-shanghai.aliyuncs.com/aicar138/YTKJ20210056/20240129/inspect/1706493979389', 'gps_location': {'latitude': 31.272511398, 'longitude': 121.623837879}}, 'hit_time': 1706493979, 'angle': 0.0, 'head_count': 0, 'subjects': [{'road_type': 'ROAD_TYPE_UNKNOWN', 'length': 0.0, 'need_push_out': True, 'angle': 0.0, 'head_count': 0, 'fall_down_number': 0, 'area': 0.0, 'type': '', 'severity_type': 'SEVERE', 'height_diff': 0, 'width': 0, 'rel_bbox': {'h': 0.054603174603174605, 'w': 0.18571428571428572, 'y': 0.6042283799913194, 'x': 0.4391269792829241}, 'status': 'NEW', 'comfort_rate': 0.0}], 'fall_down_number': 0, 'area': 0.0, 'severity_type': 'SEVERE', 'height_diff': 0, 'width': 0, 'type': '', 'comfort_rate': 0.0}]\n");
        Hit hit = hitExcelVO.convertHit();
        System.out.println(hit);
    }
}

